package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import java.util.Date;
import java.util.Map;

@RequestMapping("/login")
@RestController
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result login(@RequestBody Map map) {
        // 1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        String validateCode = (String) map.get("validateCode");
        String telephone = (String)map.get("telephone");

        String validateCodejedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (!(validateCode!=null&&validateCodejedis!=null&&validateCode.equals(validateCodejedis))){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
        System.out.println("hello");
        //2、如果验证码正确，则判断当前用户是否为会员，根据手机号查询member,如果不是会员则自动完成会员注册
        Member member = memberService.findByTelephone(telephone);
        //member为空说明不是会员,需要注册,先注册手机号和注册时间
            if (member==null){
                member=new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }

        //3、向客户端写入Cookie，内容为用户手机号,键值对形式
        Cookie cookie = new Cookie("login_member_telephone",telephone);
            //设置路径
        cookie.setPath("/");
        //4、将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
        //保存会员信息到cookie中
            //member对象转成json在转成字符串
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone,60*30,json);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
